package net.tv90.bfmccore.task;

import java.time.DayOfWeek;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public abstract class DailyTask {

    protected ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);

    public DailyTask(int hour, int minute, int second) {
        LocalDateTime now = LocalDateTime.now();
        // 获取执行时间
        LocalDateTime time =
                now.withHour(hour).withMinute(minute).withSecond(second).withNano(0);
        // 如果当前时间已经超过执行时间，则推迟到明天执行
        if(!now.isBefore(time)) {
            time = time.plusDays(1);
        }
        // 计算开始执行任务的时间差 = 执行时间 - 当前时间
        long initialDelay = Duration.between(now, time).toMillis();
        // 计算间隔时间，即 1 天的毫秒值
        long oneWeek = 24 * 3600 * 1000;

        System.out.println("开始时间：" + new Date());
        executor.scheduleAtFixedRate(() -> {
            System.out.println("执行时间：" + new Date());
            schedule();
        }, initialDelay, oneWeek, TimeUnit.MILLISECONDS);
    }

    public abstract void schedule();
}
